//
//  CookDataHelper.m
//  FoodCorner
//
//  Created by Summer on 16/3/2.
//  Copyright © 2016年 zhangchao. All rights reserved.
//

#import "CookDataHelper.h"
#import "CategoryModel.h"
#define kCategoryURL @"http://apis.juhe.cn/cook/query?key=d8ee36cb5b0598e5205ab831d684581a&menu=%@&rn=10&pn=%ld"

@interface CookDataHelper ()

@end

@implementation CookDataHelper
static CookDataHelper *instant = nil;
+(instancetype)shareCookDataHelper
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
            instant = [[CookDataHelper alloc]init];
        });
    return instant;
}
-(void)downLoadDataWithNumberOfString:(NSString *)category
                              andPage:(NSInteger)page
                              success:(void (^)())success
                               failed:(void (^)(NSString *))failed

{
    
    //传入所要解析的数据
    NSString *urlString = [NSString stringWithFormat:kCategoryURL,category,page];
    NSString *URL = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    /*
    //使用AFNetworking解析数据
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 100;
    [manager GET:URL parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        //NSLog(@"%@",downloadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *tempDicts = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableLeaves) error:nil];
        NSDictionary *tempDict = tempDicts[@"result"];
        for (NSDictionary *dic in tempDict[@"data"]) {
            CategoryModel *model = [CategoryModel new];
            [model setValuesForKeysWithDictionary:dic];
            [self.CategoryArray addObject:model];
            
        }
     
         for (NSDictionary *dict in tempArray) {
         MainListModel *model = [MainListModel new];
         [model setValuesForKeysWithDictionary:dict];
         //[model setValuesForKeysWithDictionary:dict];
         [self.mainDataArray addObject:model];
         NSLog(@"%@",model.imtro);
         }
     
        dispatch_async(dispatch_get_main_queue(), ^{
            success();
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failed([NSString stringWithFormat:@"%ld",(long)error.code]);
        
    }];
     */
    NSURL *urlStrings = [NSURL URLWithString:URL];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:urlStrings completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSDictionary *tempDicts = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
            
            if (data != nil) {
                if (_CategoryArray != nil) {
                    [self.CategoryArray removeAllObjects];
                }
                NSDictionary *tempDict = tempDicts[@"result"];
                for (NSDictionary *dic in tempDict[@"data"]) {
                    CategoryModel *model = [CategoryModel new];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.CategoryArray addObject:model];
                    
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    success();
                });
            }else
            {
                failed(@"数据获取失败");
            }
            
        });
    }];

    [dataTask resume];
}

-(NSInteger)numberOfDatas
{
    return self.CategoryArray.count;
}
-(CategoryModel *)modelOfIndex:(NSInteger)index
{
    return self.CategoryArray[index];
}

-(NSMutableArray *)CategoryArray{
    if (!_CategoryArray) {
        _CategoryArray = [NSMutableArray array];
    }
    return _CategoryArray;
}
//- (id)copyWithZone:(NSZone *)zone
//{
//    return instant;
//}
//+ (instancetype)allocWithZone:(struct _NSZone *)zone
//{
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        instant = [[CookDataHelper alloc]init];
//    });
//    return instant;
//}
@end
